"""
代码分析核心逻辑模块
使用策略模式支持不同语言的代码分析
"""
import logging
from typing import Dict, Any, Optional
from abc import ABC, abstractmethod
from llm_integration import LLMService

logger = logging.getLogger(__name__)


class CodeAnalyzerStrategy(ABC):
    """代码分析策略抽象基类（策略模式）"""
    
    @abstractmethod
    async def analyze(self, code: str, context: Optional[str] = None) -> Dict[str, Any]:
        """分析代码"""
        pass


class PythonAnalyzer(CodeAnalyzerStrategy):
    """Python代码分析策略"""
    
    def __init__(self, llm_service: LLMService):
        self.llm_service = llm_service
    
    async def analyze(self, code: str, context: Optional[str] = None) -> Dict[str, Any]:
        return await self.llm_service.analyze_code_quality(code, "python", context)


class JavaScriptAnalyzer(CodeAnalyzerStrategy):
    """JavaScript代码分析策略"""
    
    def __init__(self, llm_service: LLMService):
        self.llm_service = llm_service
    
    async def analyze(self, code: str, context: Optional[str] = None) -> Dict[str, Any]:
        return await self.llm_service.analyze_code_quality(code, "javascript", context)


class GenericAnalyzer(CodeAnalyzerStrategy):
    """通用代码分析策略"""
    
    def __init__(self, llm_service: LLMService, language: str):
        self.llm_service = llm_service
        self.language = language
    
    async def analyze(self, code: str, context: Optional[str] = None) -> Dict[str, Any]:
        return await self.llm_service.analyze_code_quality(code, self.language, context)


class CodeAnalyzer:
    """代码分析器（策略模式上下文）"""
    
    def __init__(self, llm_service: LLMService):
        self.llm_service = llm_service
        self._strategies: Dict[str, CodeAnalyzerStrategy] = {}
        self._init_strategies()
    
    def _init_strategies(self):
        """初始化各种语言的分析策略"""
        self._strategies["python"] = PythonAnalyzer(self.llm_service)
        self._strategies["javascript"] = JavaScriptAnalyzer(self.llm_service)
        self._strategies["typescript"] = GenericAnalyzer(self.llm_service, "typescript")
        self._strategies["java"] = GenericAnalyzer(self.llm_service, "java")
        self._strategies["go"] = GenericAnalyzer(self.llm_service, "go")
        self._strategies["rust"] = GenericAnalyzer(self.llm_service, "rust")
        self._strategies["cpp"] = GenericAnalyzer(self.llm_service, "cpp")
        self._strategies["c"] = GenericAnalyzer(self.llm_service, "c")
        self._strategies["php"] = GenericAnalyzer(self.llm_service, "php")
        self._strategies["ruby"] = GenericAnalyzer(self.llm_service, "ruby")
    
    async def analyze_code(
        self,
        code: str,
        language: str,
        context: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        分析代码质量
        
        Args:
            code: 代码内容
            language: 编程语言
            context: 代码上下文
        
        Returns:
            分析结果字典
        """
        language = language.lower()
        strategy = self._strategies.get(language)
        
        if not strategy:
            # 如果没有特定策略，使用通用分析器
            strategy = GenericAnalyzer(self.llm_service, language)
        
        try:
            result = await strategy.analyze(code, context)
            logger.info(f"代码分析完成，语言: {language}")
            return result
        except Exception as e:
            logger.error(f"代码分析失败: {str(e)}")
            return {
                "error": f"代码分析失败: {str(e)}",
                "score": 0
            }

